"""
Copyright (c) Cookie Yang. All right reserved.
"""

from bcc import BPF

# Define BPF program
bpf_txt = """

#define MY_STR_LEN 12
BPF_PERF_OUTPUT(events);

struct data_t {
    char str[MY_STR_LEN];
};

int hello_world_perf(struct pt_regs *ctx) {
    struct data_t data = {};
    __builtin_memcpy(&data.str, "Hello World!", sizeof(data.str));

    events.perf_submit(ctx, &data, sizeof(data));
    return 0;
}
"""


def handle_event(cpu, data, size):
    output = bpf_ctx["events"].event(data)
    print("%s" % output.str)


# Load BPF program
bpf_ctx = BPF(text=bpf_txt)
bpf_ctx.attach_kprobe(event=bpf_ctx.get_syscall_fnname("sync"),
                      fn_name="hello_world_perf")

# Print header
print("%s" % "MESSAGE")

# Open perf "events" buffer, loop with callback to handle_event
bpf_ctx["events"].open_perf_buffer(handle_event)

# Format output
while 1:
    try:
        bpf_ctx.perf_buffer_poll()
    except KeyboardInterrupt:
        print()
        exit()
